//应用配置类
import 'dart:convert';
import 'dart:io';
import 'dart:math';

import 'package:logger/logger.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:path_provider/path_provider.dart';

import 'page/entity/devcie_entity.dart';

// import 'pages/entity/devcie_entity.dart';

var logger = Logger();

class AppConfig {
  // String _appName;
  // String _packageName;
  // late String _version;
  // String _buildNumber;
  // String? _appDocumentRoot;
  // bool _debug = false;
  static late AppConfig? _instance;
  static late PackageInfo packageInfo;
  static late Directory _directory;
  int _appId = Random().nextInt(0xFFFF);
  // bool loaded = false;

  /////////
  int bluetoothStatus = 0; //蓝牙状态 1 为打开 其他值为关闭
  late DeviceType deviceType; //当前设备类型

  /////////
  ///3.0 配置信息
  int speed_3 = 1; //3.0 速度转换
  int direct_3 = 1; //3.0 方向转换
  int switch_3 = 1; //3.0 左右遥控切换
  int rightCount = 0; //3.0 右转力度
  int leftCount = 0; //3.0 左转力度
  int retote_3 = 0; //3.0 右舵旋转
  int isolate_3 = 0; //3.0 马达独立控制

  ////////
  ///4.0 配置信息
  int channelASpeed = 1; //A通道转换
  int channelBSpeed = 1; //B通道转换
  int channelCSpeed = 1; //C通道转换
  int channelDSpeed = 1; //D通道转换
  int channelALevel = 1; //A通道档位
  int channelBLevel = 0; //B通道档位
  int channelCLevel = 0; //C通道档位
  int channelDLevel = 0; //D通道档位

  int controlLockStatus = 0; //遥控锁定
  int controlLockStatus_6 = 0; //遥控锁定
  ////////
  ///6.0 配置信息
  int channelASpeed_6 = 1; //A通道转换
  int channelBSpeed_6 = 1; //B通道转换
  int channelCSpeed_6 = 1; //C通道转换
  int channelDSpeed_6 = 1; //D通道转换
  int channelESpeed_6 = 1; //E通道转换
  int channelFSpeed_6 = 1; //F通道转换

  String _language = 'en';

  // String programv3 = '';
  // String programv4 = '';
  // String programv6 = '';
  // Map<String, dynamic> programs = {};

  static get instance => _instance;

  AppConfig._initial();

  // static Future<AppConfig> loadFromPlatform() async {
  //   //print('loadFromPlatform 调用');
  //   // PackageInfo packageInfo = await PackageInfo.fromPlatform();
  //   // String? path = await getDocumentRoot();
  //   //print('packageInfo = ${packageInfo.packageName} ${packageInfo.version} path = $path');
  //   // if (loaded) {
  //   //   return;
  //   // }
  //   return await loadFromFile();
  //   // _version = packageInfo.version;
  //   // loaded = true;
  //   // _instance =
  // }

  String? getDocumentRoot() {
    return _directory.path;
    // if (_appDocumentRoot == null) {
    // Directory directory = await getApplicationDocumentsDirectory();
    // return directory.path;
    //   //Directory directory = await getExternalStorageDirectory();  //方便调试时使用
    //   _appDocumentRoot = directory.path;
    // }
    // return _appDocumentRoot;
  }

  //APP 系统分配的目录
  String get appDocumentRootSync {
    return _directory.path;
  }

  int get appId => _appId;
  String get language => _language;

  set language(String language) => _language = language;
  // String get language => _language;

  Map<String, dynamic> toJson() => {
        'appId': _appId,
        'speed_3': speed_3,
        'direct_3': direct_3,
        'switch_3': switch_3,
        'rightCount': rightCount,
        'leftCount': leftCount,
        'retote_3': retote_3,
        'channelASpeed': channelASpeed,
        'channelBSpeed': channelBSpeed,
        'channelCSpeed': channelCSpeed,
        'channelDSpeed': channelDSpeed,
        'channelALevel': channelALevel,
        'channelBLevel': channelBLevel,
        'channelCLevel': channelCLevel,
        'channelDLevel': channelDLevel,
        'controlLockStatus': controlLockStatus,
        'controlLockStatus_6': controlLockStatus_6,
        'version': packageInfo.version,
        'language': _language,
        'channelASpeed_6': channelASpeed_6,
        'channelBSpeed_6': channelBSpeed_6,
        'channelCSpeed_6': channelCSpeed_6,
        'channelDSpeed_6': channelDSpeed_6,
        'channelESpeed_6': channelESpeed_6,
        'channelFSpeed_6': channelFSpeed_6,
      };

  String toJsonString() {
    Map<String, dynamic> json = toJson();
    return jsonEncode(json);
  }

  void saveToFile() async {
    String path = _directory.path;
    File f = File('$path/config.dat');
    if (!f.existsSync()) {
      f.createSync();
    }
    String content = toJsonString();
    //print('保存配置 $content');
    //print('保存配置 $path/config.dat');
    f.writeAsStringSync(content);
  }

  static Future<AppConfig> loadFromFile() async {
    _directory = await getApplicationDocumentsDirectory();
    packageInfo = await PackageInfo.fromPlatform();
    String path = _directory.path;
    // _version = packageInfo.version;
    File file = File('$path/config.dat');
    // logger.d('配置文件路径 $path/config.dat');
    AppConfig config = AppConfig._initial();
    if (!file.existsSync()) {
      file.createSync();
      config._appId = Random().nextInt(0xFFFF);
      String content = config.toJsonString();
      logger.d('保存配置0 $content');
      file.writeAsStringSync(content);
    } else {
      String content = file.readAsStringSync();
      if (content.isEmpty) {
        config._appId = Random().nextInt(0xFFFF);
        content = config.toJsonString();
        logger.d('保存配置1 $content');
        file.writeAsStringSync(content);
      } else {
        logger.d('加载配置 $content');
        config.loadFromString(content);
      }
    }
    _instance = config;
    return config;
  }

  void loadFromString(String content) {
    Map<String, dynamic> json = jsonDecode(content);
    _appId = json['appId'];
    speed_3 = json['speed_3'];
    direct_3 = json['direct_3'];
    switch_3 = json['switch_3'];
    rightCount = json['rightCount'];
    leftCount = json['leftCount'];
    retote_3 = json['retote_3'] ?? 0;
    channelASpeed = json['channelASpeed'];
    channelBSpeed = json['channelBSpeed'];
    channelCSpeed = json['channelCSpeed'];
    channelDSpeed = json['channelDSpeed'];
    channelALevel = json['channelALevel'];
    channelBLevel = json['channelBLevel'];
    channelCLevel = json['channelCLevel'];
    channelDLevel = json['channelDLevel'];
    controlLockStatus = json['controlLockStatus'];
    controlLockStatus_6 = json['controlLockStatus_6'] ?? 0;
    _language = json['language'];
    // programv3 = json['programv3'];
    // programv4 = json['programv4'];
    // programs = json['programs'] ?? {};
    channelASpeed_6 = json['channelASpeed_6'] ?? 1;
    channelBSpeed_6 = json['channelBSpeed_6'] ?? 1;
    channelCSpeed_6 = json['channelCSpeed_6'] ?? 1;
    channelDSpeed_6 = json['channelDSpeed_6'] ?? 1;
    channelESpeed_6 = json['channelESpeed_6'] ?? 1;
    channelFSpeed_6 = json['channelFSpeed_6'] ?? 1;
  }
}
